package frontGUI;

import Function.Function;
import base.cardInfo;
import base.deposit;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.math.BigDecimal;

public class cunkuang extends JFrame {
    
    private JTextField cardIdField;
    private JTextField amountField;
    private JComboBox<String> depositTypeCombo;
    private JSpinner yearSpinner;
    private JTextArea resultArea;
    private String cardID;
    private cardInfo card;

    public cunkuang(String cardID) {
        this.cardID = cardID;
         
        // 在初始化前检查银行卡状态
        card = Function.getCardByCid(cardID);
         
        // 1. 检查银行卡是否存在
        if (card == null) {
            JOptionPane.showMessageDialog(null, "银行卡不存在", "错误", JOptionPane.ERROR_MESSAGE);
            dispose(); // 直接关闭窗口
            return;
        }
         
        // 2. 检查银行卡是否挂失
        if ("是".equalsIgnoreCase(card.getIsReportLoss())) {
            JOptionPane.showMessageDialog(null, 
                    "银行卡 " + cardID + " 已挂失，无法存款", 
                    "操作受限", 
                    JOptionPane.WARNING_MESSAGE);
            dispose(); // 直接关闭窗口
            return;
        }
        initUI();
        setVisible(true);
        
        // 确保存款金额输入框获得焦点
        SwingUtilities.invokeLater(() -> amountField.requestFocusInWindow());
    }

    private void initUI() {
        setTitle("银行存款系统 - 多功能存款");
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        setSize(650, 550); // 增加高度以容纳更多控件
        setLocationRelativeTo(null);
        setResizable(false);
        
        // 主面板布局 - 使用GridBagLayout
        JPanel mainPanel = new JPanel(new GridBagLayout());
        mainPanel.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(10, 10, 10, 10);
        gbc.fill = GridBagConstraints.HORIZONTAL;
        
        // 标题
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.gridwidth = 2;
        gbc.anchor = GridBagConstraints.CENTER;
        JLabel titleLabel = new JLabel("多功能存款操作", SwingConstants.CENTER);
        titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 24));
        titleLabel.setForeground(new Color(0, 100, 0)); // 深绿色
        mainPanel.add(titleLabel, gbc);
        
        // 银行卡信息面板
        gbc.gridx = 0;
        gbc.gridy = 1;
        gbc.gridwidth = 2;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        mainPanel.add(createCardInfoPanel(), gbc);
        
        // 存款选项面板
        gbc.gridx = 0;
        gbc.gridy = 2;
        gbc.gridwidth = 2;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        mainPanel.add(createDepositOptionsPanel(), gbc);
        
        // 结果显示面板
        gbc.gridx = 0;
        gbc.gridy = 3;
        gbc.gridwidth = 2;
        gbc.weightx = 1.0;
        gbc.weighty = 1.0;
        gbc.fill = GridBagConstraints.BOTH;
        JPanel resultPanel = createResultPanel();
        resultPanel.setPreferredSize(new Dimension(600, 150));
        mainPanel.add(resultPanel, gbc);
        
        // 按钮面板
        gbc.gridx = 0;
        gbc.gridy = 4;
        gbc.gridwidth = 2;
        gbc.weightx = 0;
        gbc.weighty = 0;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        mainPanel.add(createButtonPanel(), gbc);
        
        setContentPane(mainPanel);
    }

    private JPanel createCardInfoPanel() {
        JPanel panel = new JPanel(new GridLayout(2, 2, 10, 10));
        panel.setBorder(BorderFactory.createTitledBorder("银行卡信息"));
        
        Font labelFont = new Font("微软雅黑", Font.BOLD, 14);
        Font fieldFont = new Font("微软雅黑", Font.PLAIN, 14);
        
        // 银行卡ID
        JLabel cardIdLabel = new JLabel("银行卡ID:");
        cardIdLabel.setFont(labelFont);
        cardIdLabel.setHorizontalAlignment(SwingConstants.RIGHT);
        
        JTextField cardIdDisplay = new JTextField(cardID);
        cardIdDisplay.setFont(fieldFont);
        cardIdDisplay.setEditable(false);
        cardIdDisplay.setBackground(new Color(240, 240, 240));
        
        // 余额
        JLabel balanceLabel = new JLabel("当前余额:");
        balanceLabel.setFont(labelFont);
        balanceLabel.setHorizontalAlignment(SwingConstants.RIGHT);
        
        JTextField balanceField = new JTextField(String.format("%,.2f", card.getBalance()));
        balanceField.setFont(fieldFont);
        balanceField.setEditable(false);
        balanceField.setForeground(new Color(0, 100, 0)); // 绿色
        
        panel.add(cardIdLabel);
        panel.add(cardIdDisplay);
        panel.add(balanceLabel);
        panel.add(balanceField);
        
        return panel;
    }

    private JPanel createDepositOptionsPanel() {
        JPanel panel = new JPanel(new GridBagLayout());
        panel.setBorder(BorderFactory.createTitledBorder("存款选项"));
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(5, 5, 5, 5);
        gbc.anchor = GridBagConstraints.WEST;
        
        Font labelFont = new Font("微软雅黑", Font.BOLD, 16);
        Font fieldFont = new Font("微软雅黑", Font.PLAIN, 14);
        
        // 存款类型选择
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.weightx = 0;
        JLabel typeLabel = new JLabel("存款类型:");
        typeLabel.setFont(labelFont);
        panel.add(typeLabel, gbc);
        
        gbc.gridx = 1;
        gbc.gridy = 0;
        gbc.weightx = 1.0;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        String[] depositTypes = {"活期存款", "定活两便", "定期存款", "零存整取"};
        depositTypeCombo = new JComboBox<>(depositTypes);
        depositTypeCombo.setFont(fieldFont);
        depositTypeCombo.setSelectedIndex(0);
        depositTypeCombo.addActionListener(e -> updateYearSpinnerVisibility());
        panel.add(depositTypeCombo, gbc);
        
        // 存款年限（仅定期和零存整取需要）
        gbc.gridx = 0;
        gbc.gridy = 1;
        gbc.weightx = 0;
        gbc.fill = GridBagConstraints.NONE;
        JLabel yearLabel = new JLabel("存款年限:");
        yearLabel.setFont(labelFont);
        yearLabel.setVisible(false); // 默认隐藏
        panel.add(yearLabel, gbc);
        
        gbc.gridx = 1;
        gbc.gridy = 1;
        gbc.weightx = 1.0;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        SpinnerNumberModel spinnerModel = new SpinnerNumberModel(1, 1, 10, 1); // 1-10年
        yearSpinner = new JSpinner(spinnerModel);
        yearSpinner.setFont(fieldFont);
        yearSpinner.setVisible(false); // 默认隐藏
        panel.add(yearSpinner, gbc);
        
        // 存款金额
        gbc.gridx = 0;
        gbc.gridy = 2;
        gbc.weightx = 0;
        gbc.fill = GridBagConstraints.NONE;
        JLabel amountLabel = new JLabel("存款金额:");
        amountLabel.setFont(labelFont);
        panel.add(amountLabel, gbc);
        
        gbc.gridx = 1;
        gbc.gridy = 2;
        gbc.weightx = 1.0;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        amountField = new JTextField();
        amountField.setFont(fieldFont);
        panel.add(amountField, gbc);
        
        return panel;
    }
    
    private void updateYearSpinnerVisibility() {
        String selectedType = (String) depositTypeCombo.getSelectedItem();
        boolean showYear = "定期存款".equals(selectedType) || "零存整取".equals(selectedType);
        
        // 获取年份标签和微调器的父容器
        Container parent = yearSpinner.getParent();
        // 遍历父容器的组件，找到年份标签和微调器
        for (Component comp : parent.getComponents()) {
            if (comp instanceof JLabel && "存款年限:".equals(((JLabel) comp).getText())) {
                comp.setVisible(showYear);
            } else if (comp == yearSpinner) {
                comp.setVisible(showYear);
            }
        }
        
        // 重新验证并重绘
        parent.revalidate();
        parent.repaint();
    }

    private JPanel createResultPanel() {
        JPanel panel = new JPanel(new BorderLayout());
        panel.setBorder(BorderFactory.createTitledBorder("操作结果"));
        
        Font fieldFont = new Font("微软雅黑", Font.PLAIN, 14);
        
        // 使用滚动面板包装文本区域
        resultArea = new JTextArea(6, 50);
        resultArea.setFont(fieldFont);
        resultArea.setEditable(false);
        resultArea.setLineWrap(true);
        resultArea.setWrapStyleWord(true);
        resultArea.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
        resultArea.setBackground(new Color(240, 240, 240)); // 浅灰色背景
        
        JScrollPane scrollPane = new JScrollPane(resultArea);
        scrollPane.setBorder(BorderFactory.createLineBorder(Color.GRAY));
        
        panel.add(scrollPane, BorderLayout.CENTER);
        
        return panel;
    }

    private JPanel createButtonPanel() {
        JPanel panel = new JPanel(new FlowLayout(FlowLayout.CENTER, 30, 10));
        
        JButton depositButton = new JButton("存款");
        JButton clearButton = new JButton("清空");
        JButton closeButton = new JButton("关闭");
        
        // 设置按钮样式
        Font buttonFont = new Font("微软雅黑", Font.BOLD, 16);
        depositButton.setFont(buttonFont);
        clearButton.setFont(buttonFont);
        closeButton.setFont(buttonFont);
        
        depositButton.setBackground(new Color(50, 150, 50)); // 绿色
        depositButton.setForeground(Color.WHITE);
        clearButton.setBackground(new Color(200, 200, 200)); // 灰色
        closeButton.setBackground(new Color(200, 50, 50)); // 红色
        closeButton.setForeground(Color.WHITE);
        
        Dimension buttonSize = new Dimension(120, 40);
        depositButton.setPreferredSize(buttonSize);
        clearButton.setPreferredSize(buttonSize);
        closeButton.setPreferredSize(buttonSize);
        
        // 存款按钮事件
        depositButton.addActionListener(e -> {
            String amountStr = amountField.getText().trim();
            String depositType = (String) depositTypeCombo.getSelectedItem();
            int years = 0;
            
            if (amountStr.isEmpty()) {
                resultArea.setText("错误: 请输入存款金额");
                return;
            }
            
            // 检查年限输入
            if ("定期存款".equals(depositType) || "零存整取".equals(depositType)) {
                years = (int) yearSpinner.getValue();
                if (years <= 0) {
                    resultArea.setText("错误: 存款年限必须大于0");
                    return;
                }
            }
            
            try {
                BigDecimal amount = new BigDecimal(amountStr);
                if (amount.compareTo(BigDecimal.ZERO) <= 0) {
                    resultArea.setText("错误: 存款金额必须大于0");
                    return;
                }
                
                // 创建存款类对象
                deposit deposit = new deposit(
                    0, // ID将由数据库自动生成
                    depositType,
                    getDepositDescription(depositType, years)
                  
                );
                
                // 执行存款操作
                String result = Function.depositMoney(cardID, amount, deposit);
                resultArea.setText(result);
                
                // 清空输入框以便下次操作
                amountField.setText("");
            } catch (NumberFormatException ex) {
                resultArea.setText("错误: 请输入有效的金额数字");
            } catch (Exception ex) {
                resultArea.setText("系统错误: " + ex.getMessage());
                ex.printStackTrace();
            }
        });
        
        // 清空按钮事件
        clearButton.addActionListener(e -> {
            amountField.setText("");
            resultArea.setText("");
            amountField.requestFocusInWindow(); // 焦点回到存款金额输入框
        });
        
        // 关闭按钮事件
        closeButton.addActionListener(e -> dispose());
        
        panel.add(depositButton);
        panel.add(clearButton);
        panel.add(closeButton);
        
        return panel;
    }
    
    private String getDepositDescription(String depositType, int years) {
        switch (depositType) {
            case "活期存款":
                return "按存款日结算利息";
            case "定活两便":
                return "灵活存取";
            case "定期存款":
                return String.format("存款期%d年", years);
            case "零存整取":
                return String.format("存款期%d年", years);
            default:
                return "";
        }
    }
}